package com.yiren.dbaa.module.common.model;

import android.app.Activity;
import android.os.CountDownTimer;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.config.bean.device.UserRiskConfigBean;
import com.yiren.backstage.currency.entity.RiskNotNetTimeEntity;
import com.yiren.backstage.db.dao.RiskNotNetTimeEntityDao;
import com.yiren.backstage.db.dao.controller.CacheDbController;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.constant.G;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.module.common.contract.RiskControlContract;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.net.OkHttpUtils;
import com.yiren.dbaa.net.bean.BaseResponseBean;
import com.yiren.dbaa.net.bean.CoachRiskBean;
import com.yiren.dbaa.net.bean.StudentBean;
import com.yiren.dbaa.net.interf.StringCallback;
import com.yiren.dbaa.util.NetWorkUtil;

import org.apache.commons.lang.StringUtils;

/**
 * Describe
 *
 * @author WRX
 * @date 2022/7/5
 */
public class RiskControlModel implements RiskControlContract.Model {

    private Activity activity;
    private UserParamConfigBean userParamConfig;

    /*** 无网练车实体类 */
    private RiskNotNetTimeEntity entity;
    /*** 无网练车上次记录的时间 */
    private long startRecordTime = 0;
    /*** 倒计时时间 */
    private int millisInFuture = 24 * 60 * 60 * 1000;
    /*** 计时器,这里必须设置静态的 */
    private static CountDownTimer downTimer;
    /*** 计时器刷新频率 */
    private final long countDownInterval = 10000;

    public RiskControlModel(Activity activity) {
        this.activity = activity;
        userParamConfig = LoadConfigApi.loadUserParamConfig(activity);
    }

    @Override
    public void startRiskCountTime(CommonCallBack callBack) {
        if (!NetWorkUtil.isNetworkAvailable(activity)) {
            if (userParamConfig.getUserInfo() != null && userParamConfig.getUserInfo().getId() != null) {
                createRiskTimer();
            }
            callBack.complete();
        } else {
            getCoachRiskResult(callBack);
        }
    }

    /**
     * 获取风控结果
     *
     * @param callBack
     */
    @Override
    public void getCoachRiskResult(CommonCallBack callBack) {
        OkHttpUtils.getInstance().postJsonString(activity, AddressConstant.getCoachRiskResult(), "", new StringCallback() {
            @Override
            public void getString(String result) {
                if (StringUtils.isNotEmpty(result)) {
                    BaseResponseBean<CoachRiskBean> responseBean = new Gson().fromJson(result, new TypeToken<BaseResponseBean<CoachRiskBean>>() {
                    }.getType());
                    if (responseBean.getError() == null) {
                        CoachRiskBean coachRiskBean = responseBean.getResult();
                        UserRiskConfigBean userRiskConfig = LoadConfigApi.loadUserRiskConfig(activity);
                        if (coachRiskBean == null) { //正常用户，都不限制
                            userRiskConfig.setRiskDeviceStatus("");
                            userRiskConfig.setLockMachineReason("");
                            userRiskConfig.setForbidTestTimeReason("");
                            userRiskConfig.setForbidCouponTimeReason("");
                            userRiskConfig.setForbidFreePlayReason("");
                            deleteUserRiskData();
                        } else {
                            //风控状态规则
                            String deviceState = coachRiskBean.getDeviceState() == null ? "" : coachRiskBean.getDeviceState().toString();
                            userRiskConfig.setRiskDeviceStatus(deviceState);
                            //锁机
                            CoachRiskBean.LockMachineMapBean lockMachineMap = coachRiskBean.getLockMachineMap();
                            String lockMachineReason = (lockMachineMap == null || lockMachineMap.getReason() == null) ? "" : lockMachineMap.getReason().getText();
                            userRiskConfig.setLockMachineReason(lockMachineReason);
                            if (StringUtils.isNotEmpty(lockMachineReason)) {
                                userRiskConfig.setLockMachineUrl(lockMachineMap.getReason().getUrl());
                            }
                            //测试练车
                            CoachRiskBean.TestTimeUseMapBean testTimeUseMap = coachRiskBean.getTestTimeUseMap();
                            String testTimeReason = (testTimeUseMap == null || testTimeUseMap.getReason() == null) ? "" : testTimeUseMap.getReason().getText();
                            userRiskConfig.setForbidTestTimeReason(testTimeReason);
                            if (StringUtils.isNotEmpty(testTimeReason)) {
                                userRiskConfig.setForbidTestTimeUrl(testTimeUseMap.getReason().getUrl());
                            }
                            //体验券练车
                            CoachRiskBean.CouponTimeUseMapBean couponTimeUseMap = coachRiskBean.getCouponTimeUseMap();
                            String couponTimeReason = (couponTimeUseMap == null || couponTimeUseMap.getReason() == null) ? "" : couponTimeUseMap.getReason().getText();
                            userRiskConfig.setForbidCouponTimeReason(couponTimeReason);
                            if (StringUtils.isNotEmpty(couponTimeReason)) {
                                userRiskConfig.setForbidCouponTimeUrl(couponTimeUseMap.getReason().getUrl());
                            }
                            //免费自动播报
                            CoachRiskBean.FreePlayUseMapBean freePlayUseMap = coachRiskBean.getFreePlayUseMap();
                            String freePlayReason = (freePlayUseMap == null || freePlayUseMap.getReason() == null) ? "" : freePlayUseMap.getReason().getText();
                            userRiskConfig.setForbidFreePlayReason(freePlayReason);
                            if (StringUtils.isNotEmpty(freePlayReason)) {
                                userRiskConfig.setForbidFreePlayUrl(freePlayUseMap.getReason().getUrl());
                            }
                            if (StringUtils.isEmpty(lockMachineReason) && StringUtils.isEmpty(testTimeReason) && StringUtils.isEmpty(couponTimeReason) && StringUtils.isEmpty(freePlayReason)) {
                                deleteUserRiskData();
                            }
                        }
                        ParamConfigApi.saveUserRiskConfig(activity, userRiskConfig);
                    }
                }
                if (callBack != null) {
                    callBack.complete();
                }
            }

            @Override
            public void getFail() {
                if (callBack != null) {
                    callBack.complete();
                }
            }
        });
    }

    /**
     * 删除用户无网练车风控记录
     */
    private void deleteUserRiskData() {
        RiskNotNetTimeEntity riskNotNetTimeEntity = (RiskNotNetTimeEntity) CacheDbController.getInstance().queryByQueryBuilder(RiskNotNetTimeEntity.class, RiskNotNetTimeEntityDao.Properties.UserId.eq(userParamConfig.getUserInfo().getId()));
        if (riskNotNetTimeEntity != null) {
            CacheDbController.getInstance().delete(riskNotNetTimeEntity);
        }
    }

    /**
     * 创建风控计时器
     */
    private void createRiskTimer() {
        entity = (RiskNotNetTimeEntity) CacheDbController.getInstance().queryByQueryBuilder(RiskNotNetTimeEntity.class, RiskNotNetTimeEntityDao.Properties.UserId.eq(userParamConfig.getUserInfo().getId()));
        if (entity == null) {
            entity = new RiskNotNetTimeEntity(userParamConfig.getUserInfo().getId(), 0L);
            CacheDbController.getInstance().insert(entity);
        } else {
            startRecordTime = entity.getUseTime();
        }
        if (null == downTimer) {
            downTimer = new CountDownTimer(millisInFuture, countDownInterval) {
                @Override
                public void onTick(long millisUntilFinished) {
                    long noNetTime = startRecordTime + (millisInFuture - millisUntilFinished);
                    entity.setUseTime(noNetTime);
                    CacheDbController.getInstance().insertOrReplace(entity);
                    //获取无网练车时间
                    G.noNetTime = (int) (noNetTime / 1000);
                    if (G.noNetTime > G.maxNoNetTime) {
                        getCoachRiskResult(null);
                        this.cancel();
                    }
                }

                @Override
                public void onFinish() {
                    this.cancel();
                }
            };
            downTimer.start();
        }
    }

    @Override
    public void cancelRiskTimer() {
        if (downTimer != null) {
            downTimer.cancel();
            downTimer = null;
        }
    }

    @Override
    public void forbidStudentExam(StudentBean student, RiskControlContract.RiskControlCallBack callBack) {
        UserRiskConfigBean userRiskConfig = LoadConfigApi.loadUserRiskConfig(activity);
        String lockMachineReason = userRiskConfig.getLockMachineReason();
        if (StringUtils.isNotEmpty(lockMachineReason)) {
            String lockMachineUrl = userRiskConfig.getLockMachineUrl();
            callBack.forbidStudent(1, lockMachineReason, lockMachineUrl);
            return;
        }
        if (null != student) {
            if (student.getCode() == 0) {  //免费播报
                String freePlayReason = userRiskConfig.getForbidFreePlayReason();
                if (StringUtils.isNotEmpty(freePlayReason)) {
                    String deviceState = userRiskConfig.getRiskDeviceStatus();
                    if (StringUtils.isNotEmpty(deviceState) && (int) Float.parseFloat(deviceState) == 4) {
                        callBack.forbidStudent(3, freePlayReason, "");
                    } else {
                        String freePlayUrl = userRiskConfig.getForbidFreePlayUrl();
                        callBack.forbidStudent(2, freePlayReason, freePlayUrl);
                    }
                    return;
                } else {
                    if (G.noNetTime > G.maxNoNetTime) {
                        callBack.forbidStudent(4, "免费自动播报", "");
                        return;
                    }
                }
            } else if (student.getCode() == 1) { //体验券
                String couponTimeReason = userRiskConfig.getForbidCouponTimeReason();
                if (StringUtils.isNotEmpty(couponTimeReason)) {
                    String deviceState = userRiskConfig.getRiskDeviceStatus();
                    if (StringUtils.isNotEmpty(deviceState) && (int) Float.parseFloat(deviceState) == 4) {
                        callBack.forbidStudent(3, couponTimeReason, "");
                    } else {
                        String couponTimeUrl = userRiskConfig.getForbidCouponTimeUrl();
                        callBack.forbidStudent(2, couponTimeReason, couponTimeUrl);
                    }
                    return;
                } else {
                    if (G.noNetTime > G.maxNoNetTime) {
                        callBack.forbidStudent(5, "体验券练车", "");
                        return;
                    }
                }
            } else if (student.getCode() == 2) { //测试
                String testTimeReason = userRiskConfig.getForbidTestTimeReason();
                if (StringUtils.isNotEmpty(testTimeReason)) {
                    String deviceState = userRiskConfig.getRiskDeviceStatus();
                    if (StringUtils.isNotEmpty(deviceState) && (int) Float.parseFloat(deviceState) == 4) {
                        callBack.forbidStudent(3, testTimeReason, "");
                    } else {
                        String testTimeUrl = userRiskConfig.getForbidTestTimeUrl();
                        callBack.forbidStudent(2, testTimeReason, testTimeUrl);
                    }
                    return;
                } else {
                    if (G.noNetTime > G.maxNoNetTime) {
                        callBack.forbidStudent(6, "测试时间", "");
                        return;
                    }
                }
            }
        }
        callBack.forbidStudent(0, "", "");
    }
}
